package com.example.app.init.chain;

import com.example.app.handle.order.OrderConfirmChainHandle;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;

@Component
public final class OrderCreateChainContext<T> implements CommandLineRunner {
    @Autowired
    private ApplicationContext applicationContext;

    private final List<OrderConfirmChainHandle> orderConfirmChainHandleContext = new ArrayList<>();
    @Override
    public void run(String... args) {
        Map<String, OrderConfirmChainHandle> beans = applicationContext.getBeansOfType(OrderConfirmChainHandle.class);
        beans.forEach((beanName, bean) -> orderConfirmChainHandleContext.add(bean));
    }

    public void handler(T requestParam) {
        orderConfirmChainHandleContext.stream().sorted(Comparator.comparing(Ordered::getOrder)).forEach(bean -> bean.handler(requestParam));
    }
}
